#include "lib.h"

 int my_atoi(char *str)
{
	long  long  num = 0;
	int ret = 0;
	char *tmp = str;
	int zf = 0;

	if (str == NULL) {
		return -1;
	}
	/*skip speace*/
	while (*str == ' ') {
		str++;
	}
	
	if (*str == '-') {
		zf = 1;
		str++;
	} else if (*str == '+'){
		str++;
	}
	while (*str != '\0') {
		if (*str < '0' || *str > '9') {
			break;
		}
		num = num*10;
		num = num + (*str-'0'); 
		str++;
		if (num-1 > (int_get_max()) && zf) {
			num = int_get_min();
			break;
		} else if (num > int_get_max() && !zf) {
			num = int_get_max();
			break;
		}
	}
	if (zf && num > 0) {
		ret = num * -1;
	} else {
		ret = num;
	}
	printf("my atoi\t\"%s\"-%d-0x%x\n",tmp,ret,ret);
	return ret;
}
int main(int argc,char **argv)
{
	if (argc == 2) {
		if ((atoi(argv[1]) != my_atoi(argv[1]))) {
			printf("sysatoi\t \"%s\"-%d-0x%x\n",argv[1],atoi(argv[1]),atoi(argv[1]));
		}
	} else {
		assert_debug(atoi("12356") == my_atoi("12356"));
	}
	return 0;
}
